package com.it.travel.handle;
//package com.it.jzs.handle;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import com.it.travel.common.ConstEnum;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class AuthInterceptor implements HandlerInterceptor {
    // 密钥
//    private final String SLOT = "jzs";   // MD5加盐

//    byte[] key = "1234567890".getBytes();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//       if (request.get)
//        if (request.getRequestURL().toString().contains("/comment")) {  // 如果路径中包含comment，就不需要拦截了
//            return true;
//        }
//        String origin = request.getHeader("Origin");
//        if(origin == null) {
//            origin = request.getHeader("Referer");
//        }
//        response.setHeader("Access-Control-Allow-Origin", origin);//这里不能写*，*代表接受所有域名访问，如写*则下面一行代码无效。谨记
//        response.setHeader("Access-Control-Allow-Credentials", "true");//true代表允许携带cookie
//        System.out.println("request.getRequestURL() = " + request.getRequestURL());
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
//            System.out.println("Method:OPTIONS");
            return true;
        }

        String authorization = request.getHeader("Authorization");
//        System.out.println("authorization = " + authorization);
//         密钥
//        byte[] key = SLOT.getBytes();
        byte[] key = ConstEnum.JWT_SALT.getStr().getBytes();
// 默认验证HS265的算法
        boolean validate = false;
        try {
            validate = JWT.of(authorization).setKey(key).validate(System.currentTimeMillis());
        } catch (JWTException e) {
            throw new TokenValidateFailException();
        }
//        System.out.println("validate = " + validate);
        if (validate) {
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        List<BlogCommentVo> commentVos = CommentThreadLocal.get();
//        if (commentVos != null) {  // 线程私有的，如果存在才进行删除操作
//            System.out.println("thread");
//            CommentThreadLocal.remove();
//
//        }
//    }
}
